# -*- coding: UTF-8 -*-
# Create your views here.
from __future__ import unicode_literals
from io import BytesIO
import qrcode
from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from . import models
import hashlib
import time
from django.http import JsonResponse
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
import uuid
from django.conf import settings
import base64


# ----白板扫码保存对接----

# 接口一：登录鉴权
class AuthView(APIView):
    def post(self, request, *args, **kwargs):
        ret = {'code': None, 'msg': None}
        user = request.data.get('username')
        pwd = request.data.get('password')
        user_obj = models.User.objects.filter(user=user, pwd=pwd).first()
        print(user, pwd, user_obj)
        if not user_obj:
            ret['code'] = 1001
            ret['msg'] = 'username or password error!'
            response = JsonResponse(ret)
        else:
            m = hashlib.md5(user.encode("utf-8"))
            ctime = str(time.time())
            m.update(ctime.encode("utf-8"))
            token = m.hexdigest()
            models.Token.objects.update_or_create(user=user_obj, defaults={'token': token})
            ret['code'] = 200
            ret['msg'] = "success"
            response = JsonResponse(ret)
            response['X-Access-Token'] = token
        return response


# 判断token
class MyAuthentication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        token = request.META.get('HTTP_X_ACCESS_TOKEN')
        token_obj = models.Token.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('token error')


# 接口二：返回文件码
class FileCodeView(APIView):
    authentication_classes = [MyAuthentication, ]

    def post(self, request, *args, **kwargs):
        fileCode = uuid.uuid4().hex
        ctime = int(time.time())
        fileUploadUrl = "https://www.yiyizai.top/v1/tmp/" + fileCode + ".cwb"
        thumbnailFileUploadUrl = "https://www.yiyizai.top/v1/tmp/" + fileCode + ".jpg"
        pdfFileUploadUrl = "https://www.yiyizai.top/v1/tmp/" + fileCode + ".pdf"
        ret = {"code": 0, "description": "success", "timestamp": ctime, "data": {
            "fileCode": fileCode,
            "fileUploadUrl": fileUploadUrl,
            "thumbnailFileUploadUrl": thumbnailFileUploadUrl,
            "pdfFileUploadUrl": pdfFileUploadUrl,
        }

               }
        return JsonResponse(ret)


# 接口三：PUT上传文件
class UploadFileView(APIView):
    def put(self, request, *args, **kwargs):
        put_url = request.path_info
        dfile = put_url.split('/')[3]
        file_patch = '%s/%s' % (settings.MEDIA_ROOT, dfile)
        print(put_url, dfile, file_patch)
        with open(file_patch, 'wb')as handle:
            handle.write(request.body)
        return HttpResponse("文件上传成功")


# 接口四：上报文件信息
class FileImgView(APIView):
    authentication_classes = [MyAuthentication, ]

    def post(self, request, *args, **kwargs):
        token = request.META.get('HTTP_X_ACCESS_TOKEN')
        fileCode = request.data.get('fileCode')
        fileName = request.data.get('fileName')
        fileSize = request.data.get('fileSize')
        thumbnailFileName = request.data.get('thumbnailFileName')
        thumbnailFileSize = request.data.get('thumbnailFileSize')
        pdfFileName = request.data.get('pdfFileName')
        pdfFileSize = request.data.get('pdfFileSize')
        uploadResult = request.data.get('uploadResult')
        print(fileCode, fileName, fileSize, thumbnailFileName, thumbnailFileSize, pdfFileName, pdfFileSize)
        ret = {'code': 0, 'description': 'Success', 'timestamp': int(time.time()), 'data': token}
        if uploadResult == 'SUCCESS':
            return JsonResponse(ret)
        else:
            ret['code'] = 10001
            ret['description'] = 'file upload fail'
            return JsonResponse(ret)


# 接口五：获取二维码
class QrCodeView(APIView):
    authentication_classes = [MyAuthentication, ]

    def post(self, request, *args, **kwargs):
        fileCode = request.data.get('data')["fileCode"]
        down_url = "https://www.yiyizai.top/v1/testdown/" + fileCode + ".pdf"
        img1 = qrcode.make(down_url)
        buf1 = BytesIO()
        img1.save(buf1, format="PNG")
        image_stream1 = buf1.getvalue()
        str_img = base64.b64encode(image_stream1).decode("utf-8")
        return HttpResponse(str_img)


# 接口六：文件下载测试
class DownfileView(APIView):
    def get(self, request, *args, **kwargs):
        put_url = request.path_info
        dfile = put_url.split('/')[3]
        file_patch = '%s/%s' % (settings.MEDIA_ROOT, dfile)
        print(dfile, file_patch)
        with open(file_patch, 'rb')as f:
            file = f.read()
        response = HttpResponse(file)
        response["Content-Type"] = "image/png/jpg/cwd/pdf"
        response["Content-Disposition"] = "inline;filename=" + dfile
        return response
